﻿using Kinlo.MESDocking;
using NewLife.Model;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using UIWindows.GlobalStatics;
using UIWindows.Models.Devices;
using UIWindows.Tools.Helper;
using XingLucifer.Devices;
using XingLucifer.IBase.Enums;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace UIWindows.Services.PLC_MESHelper
{
    /// <summary>
    /// 定时获取产量信息上传
    /// </summary>
    public class ProductionHelper : HelperBase
    {

        PLCBase InjMachine { get; set; }
        //MESCollectionItemsParameterModel parameter { get; set; }

        MESProductCountData_Hour mesData_HourInteraction { get; set; }
        MESProductCountData_Day mesData_DayInteraction { get; set; }

        public ProductionHelper(
            DeviceInteractiveaddressStatic deviceInteractiveaddressStatic,
            DeviceClientModel deviceModel,
            TemporaryStatic temporaryStatic,
            ParameterStatic parameterStatic,
            DeviceConfigStatic deviceConfigStatic,
            SystemConfigStatic systemConfigStatic,
             HomeStatic homeStatic,
             Action<string, string, string, string, string, long, DateTime, string, string, string, string> log, Action<string, string, string> dialog
            ) : base(deviceInteractiveaddressStatic, deviceModel, temporaryStatic, parameterStatic, deviceConfigStatic, systemConfigStatic, homeStatic, log, dialog)
        {
            InjMachine =  deviceModel.PLC;
            mesData_HourInteraction = new MESProductCountData_Hour(_log, _dialog, machineInfo_Type);
            mesData_DayInteraction = new MESProductCountData_Day(_log, _dialog, machineInfo_Type);
        }
        public override Task Handle()
        {
            GatherCount();
            return base.Handle();
        }
        public void GatherCount()
        {
            try
            {
                //string machineInCountAddress = "DM50080";
                //string machineOkCountAddress = "DM50082";
                //string machineNgCountAddress = "DM50084";
                var addReassData = GetAddReassData("MachineInCountAddress");
                var InCounst = InjMachine.ReadUInt32(addReassData.PLCAddress, 1);

                addReassData = GetAddReassData("MachineOkCountAddress");
                var OkCounst = InjMachine.ReadUInt32(addReassData.PLCAddress, 1);

                addReassData = GetAddReassData("MachineNgCountAddress");
                var NgCounst = InjMachine.ReadUInt32(addReassData.PLCAddress, 1);

                if (InCounst != null && OkCounst != null && NgCounst != null)
                {
                    _parameter.PutIntoNumber = (int)InCounst[0];
                    _parameter.QualifiedNumber = (int)OkCounst[0];
                    _parameter.UnqualifiedNumber = (int)NgCounst[0];
                    var counts = _parameter.QualifiedNumber + _parameter.UnqualifiedNumber;
                    if (_parameter.PutIntoNumber< counts)
                    {
                        _parameter.PutIntoNumber = counts;
                    }

                    _temporaryStatic.mesCollectionItemsTemporary[(int)machineInfo_Type].PutIntoNumber = (int)InCounst[0];
                    _temporaryStatic.mesCollectionItemsTemporary[(int)machineInfo_Type].QualifiedNumber = (int)OkCounst[0];
                    _temporaryStatic.mesCollectionItemsTemporary[(int)machineInfo_Type].UnqualifiedNumber = (int)NgCounst[0];
                }
            }
            catch (Exception ex)
            {
                RunLog($"获取产量错误{ex.ToString()}");
            }
        }

        /// <summary>
        /// 生产统计上传 小时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public Task TaskCountHour_Elapsed()
        {

            try
            {
                int putIntoNumber = 0; //投入
                int qualifiedNumber = 0;//合格
                int unqualifiedNumber = 0;//不合格
                if (machineInfo_Type == MachineInfoTypes.预充装盘)
                {
                    putIntoNumber = _parameter.InCount;
                    qualifiedNumber = _parameter.OKCount;
                    unqualifiedNumber = _parameter.NGCount;
                }
                else
                {
                    putIntoNumber = _parameter.PutIntoNumber;
                    qualifiedNumber = _parameter.QualifiedNumber;
                    unqualifiedNumber = _parameter.UnqualifiedNumber;
                }
                Dictionary<string, object> mesParameters = new Dictionary<string, object>
                                {
                                    { "data", new List<Dictionary<string, object>>()
                                        {
                                               new Dictionary<string, object>()
                                               {
                                                    { "Team", _parameter.ClassTeam },
                                                    { "Shift", _parameter.Class },
                                                    { "WorkNumber", _parameter.UserName },
                                                    { "EquipmentNo", _parameter.EquipmentCode },
                                                    { "WorkOrderNo", _parameter.WorkOrder },
                                                    { "PutIntoNumber",putIntoNumber },
                                                    { "QualifiedNumber", qualifiedNumber},
                                                    { "UnqualifiedNumber",unqualifiedNumber },
                                                    { "ProductionStartTime", DateTime.Now.AddHours(-1).ToString("yyyy-MM-dd HH:mm:ss") },
                                                    { "ProductionEndTime",DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") },

                                                }
                                        }
                                    }
                                };

                Dictionary<string, object> mesParams = new Dictionary<string, object>
                {
                    { "EquipmentCode", _parameter.EquipmentCode==null?"": _parameter.EquipmentCode },
                        { "process_id", _parameter.process_id==null?"": _parameter.process_id },
                    { "parameter", mesParameters }
                };



                var result = mesData_HourInteraction.MESInteraction(_parameterStatic.MESParameter.ProductCountDataRouter,
                     _parameterStatic.MESParameter.ProductCountDataTime,
                     1, DateTime.Now, mesParams);
            }catch(Exception ex)
            {
                RunLog($"生产统计小时小时小时上传MES错误：{ex}");
            }

            try
            {
                if (_collectParamete == null)
                {

                    var entityType = GetEntityType();
                    var entity = CreateEntityType<object>();


                    //PropertyInfo propertyInData = entity.GetType().GetProperty("Operator");
                    //string valueToCompare = propertyInData.GetValue(entity)?.ToString();   // 假设你要比较的值

                    // 设置数据库表名
                    PropertyInfo tableNameProperty = entityType.Item2.GetProperty("TableName", BindingFlags.Static | BindingFlags.Public);
                    tableNameProperty.SetValue(entity, Convert.ChangeType($"{entityType.Item1.Name}_{DateTime.Now:yyyy}{DateTime.Now.GetQuarterly()}", tableNameProperty.PropertyType), null);

                    try
                    {
                        //插入数据方法
                        MethodInfo method = entityType.Item1.GetMethod("Insert");
                        object insertResult = method.Invoke(entity, null);

                        _homeStatic.AddBattery(entity, machineInfo_Type);
                    }
                    catch (Exception ex)
                    {
                        RunLog($"工艺参数插入数据库失败！！！{ex.ToString()}");
                        if (ex.InnerException != null)
                        {
                            RunLog($"内部异常：{ex.InnerException.ToString()}");
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                RunLog($"插入数据库异常！！！{ex.ToString()}");
            }
            return Task.CompletedTask;

        }

        /// <summary>
        /// 生产统计上传 天
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public Task TaskCountDay_Elapsed()
        {
            try
            {

                int putIntoNumber = 0; //投入
                int qualifiedNumber = 0;//合格
                int unqualifiedNumber = 0;//不合格
                if (machineInfo_Type == MachineInfoTypes.预充装盘)
                {
                    putIntoNumber = _parameter.InCount;
                    qualifiedNumber = _parameter.OKCount;
                    unqualifiedNumber = _parameter.NGCount;
                }
                else
                {
                    putIntoNumber = _parameter.PutIntoNumber;
                    qualifiedNumber = _parameter.QualifiedNumber;
                    unqualifiedNumber = _parameter.UnqualifiedNumber;
                }

                Dictionary<string, object> mesParameters = new Dictionary<string, object>
                                {
                                    { "data", new List<Dictionary<string, object>>()
                                        {
                                               new Dictionary<string, object>()
                                               {
                                                    { "Team", _parameter.ClassTeam },
                                                    { "Shift", _parameter.Class },
                                                    { "WorkNumber", _parameter.UserName },
                                                    { "EquipmentNo", _parameter.EquipmentCode },
                                                    { "WorkOrderNo", _parameter.WorkOrder },
                                                    { "PutIntoNumber", putIntoNumber },
                                                    { "QualifiedNumber",qualifiedNumber },
                                                    { "UnqualifiedNumber",unqualifiedNumber },
                                                    { "ProductionStartTime", DateTime.Now.AddHours(-1).ToString("yyyy-MM-dd HH:mm:ss") },
                                                    { "ProductionEndTime",DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") },

                                                }
                                        }
                                    }
                                };

                Dictionary<string, object> mesParams = new Dictionary<string, object>
                {
                  { "EquipmentCode", _parameter.EquipmentCode==null?"": _parameter.EquipmentCode },
                        { "process_id", _parameter.process_id==null?"": _parameter.process_id },
                    { "parameter", mesParameters }
                };

                var result = mesData_DayInteraction.MESInteraction(_parameterStatic.MESParameter.ProductCountData_DayRouter,
                     _parameterStatic.MESParameter.ProductCountData_DayTime,
                     1, DateTime.Now, mesParams);
            }
            catch (Exception ex)
            {
                RunLog($"生产统计天天天天上传MES错误：{ex}");
            }
            return Task.CompletedTask;
        }


    }
}
